<template>
  <div class="quiz-detail">
    <div class="page-header">
      <div class="header-left">
        <h2>{{ quiz.title || '测试详情' }}</h2>
        <el-tag :type="getQuizStatusType(quiz.status)">{{ getQuizStatusText(quiz.status) }}</el-tag>
      </div>
      <div class="header-actions">
        <el-button icon="el-icon-back" @click="goBack">返回</el-button>
        <el-button 
          :type="quiz.status === 0 ? 'success' : 'warning'"
          v-if="quiz.status !== 2"
          @click="handleChangeStatus">
          {{ quiz.status === 0 ? '开始测试' : '结束测试' }}
        </el-button>
      </div>
    </div>
    
    <!-- 题目列表 -->
    <el-card class="question-card">
      <div class="card-header">
        <h3>题目列表</h3>
      </div>
      <div v-loading="questionsLoading">
        <el-collapse v-if="questions.length > 0">
          <el-collapse-item 
            v-for="(question, index) in questions" 
            :key="question.questionId"
            :title="`题目${index+1}：${question.questionText}`">
            <div class="question-content">
              <p class="question-text">{{ question.questionText }}</p>
              
              <el-divider content-position="left">选项</el-divider>
              <div class="options-list">
                <p 
                  v-for="(option, optIndex) in parseOptions(question.options)" 
                  :key="optIndex"
                  :class="{'correct-option': String(optIndex) === question.correctAnswer}">
                  <span class="option-marker">{{ ['A', 'B', 'C', 'D'][optIndex] }}</span>
                  {{ option }}
                  <span v-if="String(optIndex) === question.correctAnswer" class="correct-marker">✓ 正确答案</span>
                </p>
              </div>
              
              <el-divider content-position="left">分值</el-divider>
              <p>{{ question.score || 10 }} 分</p>
            </div>
          </el-collapse-item>
        </el-collapse>
        <el-empty v-else description="暂无题目"></el-empty>
      </div>
    </el-card>
    
    <!-- 学生提交记录 -->
    <el-card class="submissions-card">
      <div class="card-header">
        <h3>学生提交记录</h3>
      </div>
      <div v-loading="submissionsLoading">
        <el-table
          v-if="submissions.length > 0"
          :data="submissions"
          border
          style="width: 100%">
          <el-table-column prop="studentId" label="学号" width="120"></el-table-column>
          <el-table-column prop="studentName" label="姓名" width="120"></el-table-column>
          <el-table-column prop="submitTime" label="提交时间" width="180">
            <template slot-scope="scope">
              <span v-if="scope.row.submitTime">{{ formatDate(scope.row.submitTime) }}</span>
              <el-tag v-else type="danger" size="mini">未提交</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="score" label="得分" width="100">
            <template slot-scope="scope">
              <span :class="getScoreClass(scope.row.score, scope.row.totalScore)">
                {{ scope.row.score }} / {{ scope.row.totalScore || questions.length * 10 }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="答题详情">
            <template slot-scope="scope">
              <el-button type="text" @click="showAnswerDetail(scope.row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-else description="暂无学生提交记录"></el-empty>
      </div>
    </el-card>
    
    <!-- 答题详情对话框 -->
    <el-dialog title="答题详情" :visible.sync="answerDialogVisible" width="60%">
      <div v-if="currentStudentSubmission" class="answer-details">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="学生姓名">{{ currentStudentSubmission.studentName }}</el-descriptions-item>
          <el-descriptions-item label="学号">{{ currentStudentSubmission.studentId }}</el-descriptions-item>
          <el-descriptions-item label="提交时间">{{ formatDate(currentStudentSubmission.submitTime) }}</el-descriptions-item>
          <el-descriptions-item label="得分">
            <span :class="getScoreClass(currentStudentSubmission.score, questions.length * 10)">
              {{ currentStudentSubmission.score }} / {{ questions.length * 10 }}
            </span>
          </el-descriptions-item>
        </el-descriptions>
        
        <h4>答题情况</h4>
        <el-table :data="answerDetails" border style="width: 100%">
          <el-table-column prop="questionText" label="题目" show-overflow-tooltip></el-table-column>
          <el-table-column label="学生答案" width="100">
            <template slot-scope="scope">
              <span :class="{ 'correct-text': scope.row.isCorrect, 'wrong-text': !scope.row.isCorrect }">
                {{ scope.row.studentAnswer !== undefined ? ['A', 'B', 'C', 'D'][scope.row.studentAnswer] : '未答' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="正确答案" width="100">
            <template slot-scope="scope">
              <span class="correct-text">{{ ['A', 'B', 'C', 'D'][scope.row.correctAnswer] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="结果" width="80">
            <template slot-scope="scope">
              <el-tag :type="scope.row.isCorrect ? 'success' : 'danger'" size="mini">
                {{ scope.row.isCorrect ? '正确' : '错误' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="得分" width="80">
            <template slot-scope="scope">
              {{ scope.row.isCorrect ? scope.row.score : 0 }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getQuizDetail, getQuizQuestions, getQuizSubmissions, startQuiz, endQuiz } from '@/api/quiz'
import { getStudentsByClassId } from '@/api/teacher'

export default {
  name: 'TeacherQuizDetail',
  data() {
    return {
      quizId: null,
      quiz: {},
      questions: [],
      submissions: [],
      questionsLoading: false,
      submissionsLoading: false,
      answerDialogVisible: false,
      currentStudentSubmission: null,
      answerDetails: []
    }
  },
  created() {
    this.quizId = this.$route.params.quizId;
    if (!this.quizId) {
      this.$message.error('缺少测试ID参数');
      return;
    }
    
    this.loadQuizDetail();
  },
  methods: {
    // 返回上一页
    goBack() {
      this.$router.go(-1);
    },
    
    // 加载测试详情
    loadQuizDetail() {
      getQuizDetail(this.quizId)
        .then(response => {
          if (response.code === 200) {
            this.quiz = response.data;
            console.log('测验详情数据:', JSON.stringify(this.quiz, null, 2));
            console.log('班级ID字段值:', this.quiz.classId);
            
            // 检查可能的其他字段名
            const possibleClassIdFields = ['classId', 'class_id', 'class', 'classCode', 'course_class_id'];
            possibleClassIdFields.forEach(field => {
              console.log(`检查字段 ${field}:`, this.quiz[field]);
            });
            
            this.loadQuestions();
            this.loadSubmissions();
          } else {
            this.$message.error(response.msg || '获取测试详情失败');
          }
        })
        .catch(error => {
          console.error('获取测试详情错误:', error);
          this.$message.error('获取测试详情异常，请稍后重试');
        });
    },
    
    // 加载题目列表
    loadQuestions() {
      this.questionsLoading = true;
      getQuizQuestions(this.quizId)
        .then(response => {
          if (response.code === 200) {
            this.questions = response.data || [];
          } else {
            this.$message.error(response.msg || '获取题目列表失败');
          }
        })
        .catch(error => {
          console.error('获取题目列表错误:', error);
          this.$message.error('获取题目列表异常，请稍后重试');
        })
        .finally(() => {
          this.questionsLoading = false;
        });
    },
    
    // 加载提交记录
    loadSubmissions() {
      this.submissionsLoading = true;
      
      // 先获取测验所属的班级ID
      getQuizDetail(this.quizId)
        .then(response => {
          if (response.code === 200) {
            this.quiz = response.data;
            
            // 检查各种可能的班级ID字段名
            const possibleClassIdFields = ['classId', 'class_id', 'class', 'classCode', 'course_class_id', 'courseClassId'];
            let classId;
            
            for (const field of possibleClassIdFields) {
              if (this.quiz[field] !== undefined) {
                classId = this.quiz[field];
                console.log(`找到班级ID字段: ${field} = ${classId}`);
                break;
              }
            }
            
            // 检查 classId 是否存在
            if (!classId) {
              console.log('找不到班级ID，只获取提交记录');
              // 如果没有班级ID，只获取测验提交记录
              return getQuizSubmissions(this.quizId)
                .then(submissionsRes => {
                  return [submissionsRes, { code: 200, data: [] }]; // 返回空的学生列表
                });
            }
            
            // 获取所有提交记录和班级所有学生
            return Promise.all([
              getQuizSubmissions(this.quizId),
              getStudentsByClassId(classId)
            ]);
          } else {
            this.$message.error(response.msg || '获取测试详情失败');
            return Promise.reject(new Error('获取测试详情失败'));
          }
        })
        .then(([submissionsRes, studentsRes]) => {
          // 处理提交记录
          let submissionList = [];
          if (submissionsRes.code === 200) {
            submissionList = submissionsRes.data || [];
            submissionList.forEach(submission => {
              try {
                // 解析答案
                submission.answerMap = JSON.parse(submission.answers || '{}');
              } catch (e) {
                console.error('解析答案失败:', e);
                submission.answerMap = {};
              }
            });
          }
          
          // 处理学生列表
          let studentList = [];
          if (studentsRes.code === 200) {
            studentList = studentsRes.data || [];
          }
          
          // 为每个未提交的学生创建默认记录
          if (studentList.length > 0) {
            // 创建提交学生ID的集合，用于快速查找
            const submittedStudentIds = new Set(submissionList.map(s => s.studentId));
            
            // 找出未提交的学生
            const unsubmittedStudents = studentList.filter(student => !submittedStudentIds.has(student.studentId));
            
            // 为未提交的学生创建默认记录
            const defaultSubmissions = unsubmittedStudents.map(student => ({
              quizId: this.quizId,
              studentId: student.studentId,
              studentName: student.name,
              score: 0,
              answers: '{}',
              answerMap: {},
              submitTime: null, // 未提交
              totalScore: this.questions.length * 10 // 总分
            }));
            
            // 合并所有记录
            this.submissions = [...submissionList, ...defaultSubmissions];
            console.log(`测验提交情况: 已提交${submissionList.length}人，未提交${defaultSubmissions.length}人，总共${this.submissions.length}人`);
          } else {
            this.submissions = submissionList;
          }
        })
        .catch(error => {
          console.error('获取提交记录错误:', error);
          this.$message.error('获取提交记录异常，请稍后重试');
        })
        .finally(() => {
          this.submissionsLoading = false;
        });
    },
    
    // 修改测试状态
    handleChangeStatus() {
      const statusAction = this.quiz.status === 0 ? '开始' : '结束';
      
      this.$confirm(`确定要${statusAction}此测试吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const apiMethod = this.quiz.status === 0 ? startQuiz : endQuiz;
        
        apiMethod(this.quizId)
          .then(response => {
            if (response.code === 200) {
              this.$message.success(`测试已${statusAction}`);
              this.quiz.status = this.quiz.status === 0 ? 1 : 2;
            } else {
              this.$message.error(response.msg || `${statusAction}测试失败`);
            }
          })
          .catch(error => {
            console.error(`${statusAction}测试错误:`, error);
            this.$message.error(`${statusAction}测试异常，请稍后重试`);
          });
      });
    },
    
    // 解析选项
    parseOptions(optionsStr) {
      if (!optionsStr) return [];
      
      try {
        return JSON.parse(optionsStr);
      } catch (e) {
        console.error('解析选项失败:', e);
        // 尝试使用@@分隔符解析
        if (typeof optionsStr === 'string' && optionsStr.includes('@@')) {
          return optionsStr.split('@@');
        }
        return [];
      }
    },
    
    // 获取测试状态对应的样式类型
    getQuizStatusType(status) {
      switch (Number(status)) {
        case 0: return 'info'    // 未开始
        case 1: return 'success' // 进行中
        case 2: return 'warning' // 已结束
        default: return 'info'
      }
    },
    
    // 获取测试状态对应的文字描述
    getQuizStatusText(status) {
      switch (Number(status)) {
        case 0: return '未开始'
        case 1: return '进行中'
        case 2: return '已结束'
        default: return '未知'
      }
    },
    
    // 日期格式化
    formatDate(dateString) {
      if (!dateString) return '';
      
      const date = new Date(dateString);
      return date.toLocaleString();
    },
    
    // 获取分数的样式类
    getScoreClass(score, totalScore) {
      if (score === 0) return 'score-zero';
      const percentage = (score / totalScore) * 100;
      if (percentage >= 80) return 'score-excellent';
      if (percentage >= 60) return 'score-good';
      return 'score-poor';
    },
    
    // 显示答题详情
    showAnswerDetail(submission) {
      this.currentStudentSubmission = submission;
      
      // 检查是否是未提交的学生
      if (submission.submitTime === null) {
        this.$message.info('该学生未提交测验，无法查看详情');
        return;
      }
      
      // 生成答题详情列表
      this.answerDetails = this.questions.map(question => {
        const questionId = String(question.questionId);
        const studentAnswer = submission.answerMap[questionId];
        const correctAnswer = Number(question.correctAnswer);
        const isCorrect = studentAnswer !== undefined && Number(studentAnswer) === correctAnswer;
        
        return {
          questionId,
          questionText: question.questionText,
          studentAnswer: studentAnswer !== undefined ? Number(studentAnswer) : undefined,
          correctAnswer,
          isCorrect,
          score: question.score || 10
        };
      });
      
      this.answerDialogVisible = true;
    }
  }
}
</script>

<style scoped>
.quiz-detail {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-left h2 {
  margin: 0;
  margin-right: 15px;
}

.info-card,
.question-card,
.submissions-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.card-header h3 {
  margin: 0;
  color: #333;
}

.question-content {
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 5px;
}

.question-text {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 15px;
}

.options-list p {
  margin: 10px 0;
  padding: 8px 12px;
  border-radius: 4px;
  position: relative;
}

.correct-option {
  background-color: #f0f9eb;
  border-left: 3px solid #67c23a;
}

.correct-marker {
  color: #67c23a;
  font-weight: bold;
  margin-left: 10px;
}

.option-marker {
  font-weight: bold;
  margin-right: 10px;
  display: inline-block;
  width: 20px;
  height: 20px;
  line-height: 20px;
  text-align: center;
  border-radius: 50%;
  background-color: #eee;
}

.correct-text {
  color: #67c23a;
  font-weight: bold;
}

.wrong-text {
  color: #f56c6c;
  font-weight: bold;
}

.answer-details {
  padding: 10px;
}

.score-excellent {
  color: #67c23a;
  font-weight: bold;
}

.score-good {
  color: #e6a23c;
  font-weight: bold;
}

.score-pass {
  color: #409eff;
  font-weight: bold;
}

.score-low {
  color: #f56c6c;
  font-weight: bold;
}
</style> 